package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.OptionsPickerView;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.AuthStateUtils;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.ui.dialog.AuthCodeImageDialog;
import com.cardbaobao.cardbabyclient.model.CityInfo;
import com.cardbaobao.cardbabyclient.utils.AnimationUtil;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.SoftKeyboardUtils;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.ViewUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 9:05.
 * 社保、公积金查询
 */
public class InquiriesActivity extends BaseActivity {
    public static final String CHANNEL_TYPE_S="channel_type";
    public static final String CHANNEL_SHE_BAO="SHE_BAO";//社保查询
    public static final String CHANNEL_GJJ="GJJ";//公积金查询
    private String channelType;

    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.et_real_name)
    EditText etRealName;
    @BindView(R.id.et_id_no)
    EditText etIdNo;

    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;

    @BindView(R.id.view_pager)
    ViewPager viewPager;

    @BindView(R.id.cb_agreement)
    CheckBox cbAgreement;

    @BindView(R.id.tv_agreement)
    TextView tvAgreement;//协议

    @BindView(R.id.tv_tips)
    TextView tvTips;//注意事项

    private int indicatorHeight;
    private int viewpagerHeight;

    @Override
    protected void onResume() {
        super.onResume();
        if (CHANNEL_GJJ.equals(channelType)) {
            GoogleAnalyticsUtil.setScreenName(Google.ACCUM_FUND_QUERY);
        } else {
            GoogleAnalyticsUtil.setScreenName(Google.SOCIAL_QUERY);
        }

    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        ImmersionBar.with(this).statusBarDarkFont(true, Constant.STATUS_BAR_FONT_ALPHA).keyboardEnable(true).init();
        channelType = getIntent().getStringExtra(CHANNEL_TYPE_S);
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (savedInstanceState != null) {
            channelType = savedInstanceState.getString(CHANNEL_TYPE_S);
            taskId = savedInstanceState.getString("taskId");
        }
        if (CHANNEL_GJJ.equals(channelType)) {
            //公积金查询
            mCurrentPageId=Self.Page.app_provident_fund_inquiry_page;
            titleBar.setTitleText("公积金查询");
            tvAgreement.setText("《公积金查询服务协议》");
            tvTips.setText("温馨提示:\n" +
                    "1、忘记账号可咨询所在任职公司人事获取您的公积金账号。\n" +
                    "2、忘记密码可登录当地公积金网站进行密码重置后查询。\n" +
                    "3、已注册用户可使用公积金登录名、密码等信息登录查询。\n" +
                    "4、可选省市之外的地区将会逐步开通，敬请关注。"
            );
        } else {
            //社保查询
            mCurrentPageId= Self.Page.app_social_security_inquiry_page;
            titleBar.setTitleText("社保查询");
            tvAgreement.setText("《社保查询服务协议》");
            tvTips.setText("温馨提示:\n" +
                    "1、未注册或忘记密码，可登录当地社保网站进行注册设置，亦可致电12333进行咨询。\n" +
                    "2、已注册用户可使用社保登录名、密码等信息登录查询。\n" +
                    "3、可选省市之外的地区将会逐步开通，敬请关注。"
            );
        }
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, metrics);

        addRealNameWatcher();
        addIdNoWatcher();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_inquiries;
    }

    private void addRealNameWatcher() {
        etRealName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String realName = s.toString().trim();
                if (realName.length() >= 2 && pagerViews != null && pagerViews.size() > 0) {
                    for (LinearLayout l : pagerViews) {
                        for (int i = 0, count = l.getChildCount(); i < count; i++) {
                            View view = l.getChildAt(i);
                            if (view.getTag() != null) {
                                LoginElement element = (LoginElement) view.getTag();
                                if (element.label.contains("姓名")) {
                                    ((TextView) view).setText(realName);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    private void addIdNoWatcher() {
        etIdNo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String idNo = s.toString().trim();
                if (RegularUtil.isIdNumber(idNo) && pagerViews != null && pagerViews.size() > 0) {
                    for (LinearLayout l : pagerViews) {
                        for (int i = 0, count = l.getChildCount(); i < count; i++) {
                            View view = l.getChildAt(i);
                            if (view.getTag() != null) {
                                LoginElement element = (LoginElement) view.getTag();
                                if (element.label.contains("身份证")) {
                                    ((TextView) view).setText(idNo);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    private boolean checkName() {
        boolean result = false;
        String text = etRealName.getText().toString().trim();
        if (TextUtils.isEmpty(text)) {
            ToastUtil.showToast("请输入姓名");
        } else {
            if (text.length() >= 2) {
                result = true;
            } else {
                ToastUtil.showToast("姓名格式错误，请重新输入");
            }
        }
        return result;
    }

    private boolean checkIdNo() {
        boolean result = false;
        String idNo = etIdNo.getText().toString().trim();
        if (TextUtils.isEmpty(idNo)) {
            ToastUtil.showToast("请输入身份证号码");
        } else {
            if (RegularUtil.isIdNumber(idNo)) {
                result = true;
            } else {
                ToastUtil.showToast("身份证号码格式不正确，请重新输入");
            }
        }
        return result;
    }

    @OnClick({R.id.ll_city, R.id.tv_agreement, R.id.bt_next_step})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_city:
                //选择城市
                SoftKeyboardUtils.hideSoftKeyboard(view);
                if (provinces.size() > 0) {
                    showCityPicker();
                } else {
                    loadCityData(true, channelType);
                }
                break;
            case R.id.tv_agreement:
                //协议
                initIntent();
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                if (tvAgreement.getText().toString().contains("社保")) {
                    //社保查询服务协议
                    SelfUtils.buriedClickData(Self.Action.app_click_social_security_inquiry_agreement,
                            Self.Action.app_click_social_security_inquiry_agreement_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    mIntent.putExtra("webUrl", URLUtil.DATA_PARSER_AGREEMENT);
                    mIntent.putExtra("title", "社保查询服务协议");
                    mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 3);
                } else {
                    //公积金查询服务协议
                    SelfUtils.buriedClickData(Self.Action.app_click_provident_fund_inquiry_agreement,
                            Self.Action.app_click_provident_fund_inquiry_agreement_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    mIntent.putExtra("webUrl", URLUtil.DATA_PARSER_AGREEMENT);
                    mIntent.putExtra("title", "公积金查询服务协议");
                    mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 4);
                }
                mContext.startActivity(mIntent);
                break;
            case R.id.bt_next_step:
                //下一步
                if (cbAgreement.isChecked()) {
                    if (loginTypes.size() == 0) {
                        //获取登录要素
                        if (checkCity() && checkName() && checkIdNo()) {
                            loadLoginElements(channelType, selectedCity.getChannel_code());
                        }
                    } else {
                        //创建任务--》爬取
                        if (checkName() && checkIdNo()) {
                            if(CHANNEL_GJJ.equals(channelType)){
                                SelfUtils.buriedClickData(Self.Action.app_click_provident_fund_inquiry,
                                        Self.Action.app_click_provident_fund_inquiry_des,
                                        mEnterPageTime,
                                        mCurrentPageId,
                                        mPrePageId);
                            }else if(CHANNEL_SHE_BAO.equals(channelType)){
                                SelfUtils.buriedClickData(Self.Action.app_click_social_security_inquiry,
                                        Self.Action.app_click_social_security_inquiry_des,
                                        mEnterPageTime,
                                        mCurrentPageId,
                                        mPrePageId);
                            }
                            //动态输入检查
                            if (pagerViews.size() > 0) {
                                boolean error = false;
                                Map<String, Object> params = new HashMap<>();
                                int current = viewPager.getCurrentItem();
                                LoginType loginType = loginTypes.get(current);
                                LinearLayout pagerView = pagerViews.get(current);
                                params.put("login_type", loginType.loginValue);
                                for (int i = 0, size = pagerView.getChildCount(); i < size; i++) {
                                    View v = pagerView.getChildAt(i);
                                    if (v instanceof EditText) {
                                        EditText editText = (EditText) v;
                                        LoginElement element = (LoginElement) editText.getTag();
                                        String text = editText.getText().toString().trim();
                                        if (TextUtils.isEmpty(text)) {
                                            error = true;
                                            ToastUtil.showToast("请输入" + element.label);
                                            break;
                                        } else {
                                            params.put(element.name, text);
                                        }
                                    } else if (v instanceof TextView) {
                                        TextView textView = (TextView) v;
                                        LoginElement element = (LoginElement) textView.getTag();
                                        String text = textView.getText().toString().trim();
                                        if (TextUtils.isEmpty(text)) {
                                            error = true;
                                            ToastUtil.showToast("请输入" + element.label);
                                            break;
                                        } else {
                                            params.put(element.name, text);
                                        }
                                    }
                                }
                                if (!error) {
                                    params.put("channel_type", channelType);
                                    params.put("channel_code", selectedCity.getChannel_code());
                                    params.put("real_name", etRealName.getText().toString().trim());
                                    params.put("identity_code", etIdNo.getText().toString().trim());
                                    params.put("user_mobile", "");
                                    params.put("user_id", mApplication.getUser().getID());
                                    createTask(params);

                                    if ("GJJ".equals(channelType)) {
                                        GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_SERVICE, Google.ACTION_ACCUM_QUERY);
                                    } else {
                                        GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_SERVICE, Google.ACTION_SOCIAL_QUERY);
                                    }

                                }
                            }
                        }
                    }
                } else {
                    ToastUtil.showToast("需要同意" + tvAgreement.getText().toString() + "才能进行下一步操作");
                }
                break;
        }
    }

    //获取城市信息
    private void loadCityData(final boolean showCityPicker, String channelType) {
        showProgressDialog(false);
        Observable<String> observable= Api.getAuthCityList(channelType);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                List<CityInfo> cityInfoList = JSON.parseArray(s, CityInfo.class);
                CityInfo cityInfo;
                if (cityInfoList != null && cityInfoList.size() > 0) {
                    for (int i = 0, size = cityInfoList.size(); i < size; i++) {
                        cityInfo = cityInfoList.get(i);
                        //先取出省级城市
                        if (cityInfo.getParent_id() == 0) {
                            provinces.add(cityInfo);
                        }
                    }
                    //根据省级城市，取出其对应的市级城市
                    int parentId;
                    ArrayList<CityInfo> list;
                    for (int i = 0, size = provinces.size(); i < size; i++) {
                        parentId = provinces.get(i).getId();
                        list = new ArrayList<>();
                        for (int j = 0, jSize = cityInfoList.size(); j < jSize; j++) {
                            cityInfo = cityInfoList.get(j);
                            if (cityInfo.getParent_id() == parentId) {
                                list.add(cityInfo);
                            }
                        }
                        cities.add(list);
                    }
                }
                dismissProgressDialog();
                if (showCityPicker) {
                    showCityPicker();
                }
            }
        });
    }

    private OptionsPickerView pickerView;
    private ArrayList<CityInfo> provinces = new ArrayList<>();
    private ArrayList<ArrayList<CityInfo>> cities = new ArrayList<>();

    private void showCityPicker() {
        if (pickerView == null) {
            OptionsPickerView.OnOptionsSelectListener listener =
                    new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            clearLoginTypes();
                            selectedCity = cities.get(options1).get(options2);
                            tvCity.setTextColor(0xff222222);
                            tvCity.setText(selectedCity.getPickerViewText());
                        }
                    };
            int textColor = ContextCompat.getColor(mContext, R.color.color_7EC1F9);
            int dividerColor = ContextCompat.getColor(mContext, R.color.color_E5E5E5);
            int textSize = 17;//17sp
            int bgColor = 0xFFFFFFFF;
            pickerView = new OptionsPickerView.Builder(mContext, listener)
                    .setCancelText("取消")
                    .setCancelColor(textColor)
                    .setSubCalSize(textSize)
                    .setSubmitColor(textColor)
                    .setSubCalSize(textSize)
                    .setSubmitText("完成")
                    .setBgColor(bgColor)
                    .setContentTextSize(textSize)
                    .setDividerColor(dividerColor)
                    .build();
            pickerView.setPicker(provinces, cities);
        }
        if (!pickerView.isShowing()) {
            pickerView.show();
        }
    }


    private CityInfo selectedCity;

    private boolean checkCity() {
        boolean result = false;
        if (selectedCity == null) {
            ToastUtil.showToast("请选择城市");
        } else {
            result = true;
        }
        return result;
    }

    //登录方式
    private class LoginType {
        private String loginName;//登录方式名称
        private String loginValue;//登录方式的值
        private List<LoginElement> elements;

        public void setElements(List<LoginElement> elements) {
            this.elements = elements;
        }

        public void setLoginName(String loginName) {
            this.loginName = loginName;
        }

        public void setLoginValue(String loginValue) {
            this.loginValue = loginValue;
        }
    }

    //登录要素
    private class LoginElement {
        private String label;
        private String name;
        private String type;

        LoginElement(String label, String name, String type) {
            this.label = label;
            this.name = name;
            this.type = type;
        }
    }

    //获取登录要素
    private void loadLoginElements(String channelType, String channelCode) {
        showProgressDialog(false);
        Observable<String> observable=Api.getLoginElements(channelType,channelCode);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json = JSON.parseObject(s);
                if (json.getIntValue("code") == 2005) {
                    //获取登录要素成功
                    JSONArray array = json.getJSONArray("data");
                    for (int i = 0, size = array.size(); i < size; i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        LoginType type = new LoginType();
                        type.setLoginName(jsonObject.getString("label") + "登录");
                        type.setLoginValue(jsonObject.getString("value"));
                        List<LoginElement> elements = new ArrayList<>();
                        JSONArray fields = jsonObject.getJSONArray("fields");
                        for (int j = 0, fSize = fields.size(); j < fSize; j++) {
                            JSONObject field = fields.getJSONObject(j);
                            elements.add(new LoginElement(
                                    field.getString("label"),
                                    field.getString("name"),
                                    field.getString("type")));
                        }
                        type.setElements(elements);
                        loginTypes.add(type);
                    }
                    //获取登录要素成功后，计算viewPage最大高度
                    int loginElementSize;//每种登录方式中有多少个登录要素
                    int perHeight=DensityUtil.dp2px(45);//每个登录要素的高度
                    int temp;//记录某种登录方式中登录要素占的总高度
                    int max=0;//记录各种登录方式中登录要素占的最大高度
                    for(int i=0;i<loginTypes.size();i++){
                        loginElementSize=loginTypes.get(i).elements.size();
                        temp=loginElementSize*perHeight+DensityUtil.dp2px(loginElementSize-1);
                        max=temp>max?temp:max;
                    }
                    viewpagerHeight=max;
                    viewPager.getLayoutParams().height=viewpagerHeight;
                    showIndicator();
                } else {
                    ToastUtil.showToast(json.getString("message"));
                }
            }
        });
    }

    private List<LoginType> loginTypes = new ArrayList<>();
    private List<LinearLayout> pagerViews = new ArrayList<>();

    private void showIndicator() {
        for (int i = 0, size = loginTypes.size(); i < size; i++) {
            LinearLayout linearLayout = new LinearLayout(mContext);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            LinearLayout.LayoutParams llParams =
                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.MATCH_PARENT);
            linearLayout.setLayoutParams(llParams);
            List<LoginElement> elements = loginTypes.get(i).elements;

            int margin40 = DensityUtil.dp2px(20);
            LinearLayout.MarginLayoutParams textParams =
                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                            DensityUtil.dp2px(mContext, 45.0f));
            textParams.leftMargin = margin40;
            int dividerColor = Constant.DIVIDER_COLOR;
            LinearLayout.MarginLayoutParams dividerParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, 1);
            dividerParams.leftMargin = margin40;
            for (int j = 0, jSize = elements.size(); j < jSize; j++) {
                LoginElement element = elements.get(j);
                if (element.label.contains("身份证") || element.label.contains("姓名")) {
                    TextView textView = produceTextView(textParams, element);
                    linearLayout.addView(textView);
                } else {
                    EditText editText = produceEditText(textParams, element);
                    linearLayout.addView(editText);
                }
                View divider = new View(mContext);
                divider.setLayoutParams(dividerParams);
                divider.setBackgroundColor(dividerColor);
                linearLayout.addView(divider);
            }
            pagerViews.add(linearLayout);
        }
        settingViewPagerViews();
        AnimationUtil.changeViewHeightAnimatorStart(magicIndicator, 0, indicatorHeight);
        AnimationUtil.changeViewHeightAnimatorStart(viewPager, 0, viewpagerHeight);
    }

    private EditText produceEditText(LinearLayout.MarginLayoutParams textParams,
                                     LoginElement element) {
        int textColor = 0xff222222;
        int textHintColor = 0xffdddddd;
        int padding = getResources().getDimensionPixelSize(R.dimen.dimen_10_dp);
        Drawable backGround = new ColorDrawable(0x00000000);
        EditText editText = new EditText(mContext);
        editText.setLayoutParams(textParams);
        editText.setGravity(Gravity.CENTER_VERTICAL);
        editText.setTag(element);
        editText.setHint("请输入" + element.label);
        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15.0f);
        editText.setTextColor(textColor);
        editText.setHintTextColor(textHintColor);
        editText.setMaxLines(1);
        editText.setPadding(padding, 0, 0, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            editText.setBackground(backGround);
        } else {
            editText.setBackgroundDrawable(backGround);
        }
        if ("password".equals(element.type)) {
            ViewUtil.toggleEditTextInputType(editText, true);
        } else {
            ViewUtil.toggleEditTextInputType(editText, false);
        }
        editText.setText("");
        return editText;
    }

    private TextView produceTextView(LinearLayout.MarginLayoutParams textParams,
                                     LoginElement element) {
        int textColor = 0xff222222;
        int padding = getResources().getDimensionPixelSize(R.dimen.dimen_10_dp);
        Drawable backGround = new ColorDrawable(0x00000000);
        TextView textView = new TextView(mContext);
        textView.setLayoutParams(textParams);
        textView.setGravity(Gravity.CENTER_VERTICAL);
        textView.setTag(element);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15.0f);
        textView.setTextColor(textColor);
        textView.setMaxLines(1);
        textView.setPadding(padding, 0, 0, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            textView.setBackground(backGround);
        } else {
            textView.setBackgroundDrawable(backGround);
        }
        if (element.label.contains("身份证")) {
            textView.setText(etIdNo.getText().toString().trim());
        } else if (element.label.contains("姓名")) {
            textView.setText(etRealName.getText().toString().trim());
        }
        return textView;
    }

    private ViewPagerAdapter adapter;

    //设置viewPager
    private void settingViewPagerViews() {
        if (adapter == null) {
            adapter = new ViewPagerAdapter();
            viewPager.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        viewPager.setCurrentItem(0);
        final CommonNavigator titleNavigator = new CommonNavigator(mContext);
        titleNavigator.setAdjustMode(true);
        titleNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return loginTypes.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int i) {
                SimplePagerTitleView titleView = new ColorTransitionPagerTitleView(mContext);
                titleView.setNormalColor(0xff999999);
                titleView.setSelectedColor(0xffff9e27);
                titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14.0f);
                titleView.setGravity(Gravity.CENTER);
                titleView.setText(loginTypes.get(i).loginName);
                titleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPager.setCurrentItem(i);
                    }
                });
                return titleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_MATCH_EDGE);
                indicator.setColors(0xffff9e27);
                return indicator;
            }
        });
        magicIndicator.setNavigator(titleNavigator);
        ViewPagerHelper.bind(magicIndicator, viewPager);
    }

    private class ViewPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return pagerViews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = null;
            if (pagerViews.size() > 0) {
                view = pagerViews.get(position);
                container.addView(view);
            }
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (pagerViews.size() > 0) {
                View view = pagerViews.get(position);
                container.removeView(view);
            }
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }

    //清除登录要素
    private void clearLoginTypes() {
        loginTypes.clear();
        pagerViews.clear();
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        viewPager.removeAllViews();
        if (magicIndicator.getLayoutParams().height != 0) {
            AnimationUtil.changeViewHeightAnimatorStart(magicIndicator, indicatorHeight, 0);
        }
        if (viewPager.getLayoutParams().height != 0) {
            AnimationUtil.changeViewHeightAnimatorStart(viewPager, viewpagerHeight, 0);
        }
    }

    private String taskId;

    //创建任务
    private void createTask(final Map<String, Object> params) {
        showProgressDialog(false);
        Observable<String> observable=Api.createTask(params);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                JSONObject jsonObject = JSON.parseObject(s);
                int code = jsonObject.getIntValue("code");
                if (code == 0) {
                    //创建任务成功
                    taskId = jsonObject.getString("task_id");
                    crawling(params);
                } else {
                    dismissProgressDialog();
                    switch (code) {
                        case 2405:
                            //身份证号码缺失或格式错误
                            ToastUtil.showToast("身份证号码不正确");
                            break;
                        case 2406:
                            //姓名缺失或格式错误
                            ToastUtil.showToast("姓名不正确");
                            break;
                        case 2407:
                            //手机号码缺失或格式错误
                            ToastUtil.showToast("手机号码不正确");
                            break;
                        case 2502:
                            //所在区域暂时不支持
                            ToastUtil.showToast("所在区域暂时不支持");
                            break;
                    }
                }
            }
        });
    }

    //登录爬取
    private void crawling(final Map<String, Object> params) {
        if(params.containsKey("real_name")){
            params.remove("real_name");
        }
        if(params.containsKey("identity_code")){
            params.remove("identity_code");
        }
        params.put("task_id",taskId);
        params.put("task_flag",1);
        Observable<String> observable=Api.crawling(params);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json = JSON.parseObject(s);
                int code = json.getIntValue("code");
                if (AuthStateUtils.isSuccess(code)) {
                    //爬取成功0
                    initIntent();
                    mIntent.setClass(mContext, InquiriesSuccessActivity.class);
                    mIntent.putExtra(InquiriesActivity.CHANNEL_TYPE_S, channelType);
                    startActivity(mIntent);
                    finish();
                } else {
                    handleCrawlResult(code, json);
                }
            }
        });
    }


    private AuthCodeImageDialog authCodeImageDialog;

    //显示验证码输入dialog
    private void showAuthCodeDialog() {
        if (authCodeImageDialog == null) {
            authCodeImageDialog = new AuthCodeImageDialog(mContext);
            authCodeImageDialog.setButtonClickedListener(new AuthCodeImageDialog.OnAuthCodeButtonClicked() {
                @Override
                public void onRefreshButtonClicked() {
                    showProgressDialog(false);
                    refreshAuthCode(taskId);
                }

                @Override
                public void onCommitButtonClicked(String authCode) {
                    showProgressDialog(false);
                    crawlingWithCode(authCode, taskId, channelType);
                }
            });
            authCodeImageDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    authCodeImageDialog.callSoftKeyBoard();
                }
            });
        }
        if (!authCodeImageDialog.isShowing()) {
            authCodeImageDialog.clearText();
            authCodeImageDialog.show();
        }
    }

    //隐藏验证码输入dialog
    private void dismissAuthCodeDialog() {
        if (authCodeImageDialog != null && authCodeImageDialog.isShowing()) {
            authCodeImageDialog.dismiss();
        }
    }

    //处理爬取结果
    private void handleCrawlResult(int code, JSONObject json) {
        switch (code) {
            case 101:
                //输入验证码
                showAuthCodeDialog();
                byte[] bytes = Base64.decode(json.getJSONObject("data").getString("auth_code"),
                        Base64.DEFAULT);
                if (authCodeImageDialog != null && authCodeImageDialog.isShowing()) {
                    authCodeImageDialog.setAuthImage(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
                }
                break;
            case 104:
                //请求验证码失败
                ToastUtil.showToast("请求验证码失败，请稍后重试");
                break;
            case 112:
                //账号或密码错误
                dismissAuthCodeDialog();
                ToastUtil.showToast("账号或密码错误，请重新输入");
                break;
            case 113:
                //登录失败
                dismissAuthCodeDialog();
                ToastUtil.showToast(ApplicationHelper.getApplicationContext().getString(R.string.string_request_data_fail));
                break;
            case 116:
                //身份证或姓名校验失败
                dismissAuthCodeDialog();
                ToastUtil.showToast("身份证或姓名错误，请重新输入");
                break;
            case 122:
                //图片验证码错误或过期
                ToastUtil.showToast("验证码错误，请重新输入");
                showProgressDialog(false);
                refreshAuthCode(taskId);
                break;
            case 2414:
                //任务id缺失或无效
                dismissAuthCodeDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
                break;
            default:
                dismissAuthCodeDialog();
                ToastUtil.showToast(json.getString("message"));
                break;
        }
    }

    //带验证码的登录爬取
    private void crawlingWithCode(String authCode, String taskId, final String channel_type) {
        showProgressDialog(false);
        Observable<String> observable=
                Api.crawling(mApplication.getUser().getID(),
                        authCode,
                        taskId,
                        channel_type,false);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json = JSON.parseObject(s);
                int code = json.getIntValue("code");
                if (AuthStateUtils.isSuccess(code)) {
                    //爬取成功0
                    dismissAuthCodeDialog();
                    initIntent();
                    mIntent.setClass(mContext, InquiriesSuccessActivity.class);
                    mIntent.putExtra(CHANNEL_TYPE_S, channelType);
                    startActivity(mIntent);
                    finish();
                } else {
                    handleCrawlResult(code, json);
                }
            }
        });
    }

    private void refreshAuthCode(String taskId) {
        showProgressDialog(false);
        Observable<String> observable=Api.refreshAuthCode(taskId);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast("获取验证码失败，请稍后重试");
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json = JSON.parseObject(s);
                int code = json.getIntValue("code");
                switch (code) {
                    case 101:
                        //请求图片验证码成功
                        byte[] bytes = Base64.decode(json.getJSONObject("data").getString("auth_code"),
                                Base64.DEFAULT);
                        showAuthCodeDialog();
                        authCodeImageDialog.setAuthImage(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
                        break;
                    case 104:
                        //请求图片验证码失败
                        ToastUtil.showToast(json.getString("message"));
                        break;
                    case 127:
                        //请求验证码超过重试次数限制
                        ToastUtil.showToast(json.getString("message"));
                        break;
                }
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(CHANNEL_TYPE_S, channelType);
        outState.putString("taskId", taskId);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        channelType = savedInstanceState.getString(CHANNEL_TYPE_S);
        taskId = savedInstanceState.getString("taskId");
    }
}
